package com.wei.czz.framework.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.tool.PageQuery;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.framework.common.handler.redis.RedisHandler;
import com.wei.czz.common.vo.blog.tag.TagFormVo;
import com.wei.czz.framework.blog.dao.TagDao;
import com.wei.czz.framework.blog.entity.TagEntity;
import com.wei.czz.framework.blog.service.TagService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-03-15 10:29:26
 * className: TagServiceImpl 博客标签操作请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("tagService")
@AllArgsConstructor
public class TagServiceImpl extends ServiceImpl<TagDao, TagEntity> implements TagService {

    private static final Logger log = LoggerFactory.getLogger(TagServiceImpl.class);

    private final RedisHandler redisHandler;

    @Override
    public void saveOrEdit(TagEntity tag) {
        if (Objects.isNull(tag.getId())) {
            int count = baseMapper.insert(tag);
            log.info("保存博客标签完成。count={}", count);
        } else {
            int count = baseMapper.updateById(tag);
            log.info("修改博客标签完成。count={}", count);
        }
    }

    @Override
    public TagEntity get(Long id) {
        TagEntity tag = baseMapper.selectById(id);
        if (Objects.isNull(tag)) {
            log.info("博客标签不存在");
            throw new CzzException(ResultEnum.NOT_FOUND.getCode(), "博客标签不存在，请确认");
        }
        if (CommonEnum.ONE.getValue().equals(tag.getDeleteStatus())) {
            log.info("博客标签已被删除");
            throw new CzzException(ResultEnum.NOT_FOUND.getCode(), "博客标签已被删除，请确认");
        }
        return tag;
    }

    @Override
    public TagEntity find(String name) {
        LambdaQueryWrapper<TagEntity> tagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagLambdaQueryWrapper.eq(TagEntity::getName, name)
                .eq(TagEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<TagEntity> tagList = baseMapper.selectList(tagLambdaQueryWrapper);
        log.info("查询标签完成。list.size={}", tagList.size());
        if (tagList.isEmpty()) {
            return null;
        }
        return tagList.get(0);
    }

    @Override
    public List<TagEntity> getTagList(List<String> tagIdList) {
        List<TagEntity> tagList = baseMapper.selectBatchIds(tagIdList);
        if (tagList.isEmpty()) {
            log.info("查询博客标签列表结果为空。tagIdList={}", tagIdList);
        }
        return tagList;
    }

    @Override
    public PageDto<TagEntity> getPageList(TagFormVo tagFormVo) {

        // 构造mp分页对象
        Page<TagEntity> page = PageQuery.initPage(tagFormVo);

        LambdaQueryWrapper<TagEntity> tagLambdaWrapper = new LambdaQueryWrapper<>();
        // 匹配 标签类型（’系统标签‘）和 模糊查询标签名称 字段
        tagLambdaWrapper.like(StringUtils.isNotBlank(tagFormVo.getWord()), TagEntity::getName, tagFormVo.getWord())
                .eq(Objects.nonNull(tagFormVo.getStatus()), TagEntity::getStatus, tagFormVo.getStatus())
                .eq(TagEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 分页查询
        baseMapper.selectPage(page, tagLambdaWrapper);
        log.info("分页查询博客标签完成。totalNum={} list.size={}", page.getTotal(), page.getRecords().size());

        return new PageDto<>(page);
    }

    @Override
    public List<TagEntity> getList() {
        LambdaQueryWrapper<TagEntity> tagLambdaWrapper = new LambdaQueryWrapper<>();
        tagLambdaWrapper.eq(TagEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<TagEntity> tagList = baseMapper.selectList(tagLambdaWrapper);
        log.info("查询所有博客标签完成。list.size={}", tagList.size());

        return tagList;
    }

    @Override
    public Integer getNextSort() {
        Integer nextSort = baseMapper.getMaxSort(CommonEnum.ZERO.getValue());
        if (nextSort == null) {
            nextSort = 0;
        }
        return nextSort + 1;
    }

    @Transactional
    @Override
    public void batchUpdate(List<TagEntity> tagList) {
        boolean bool = this.updateBatchById(tagList);
        log.info("批量更新博客标签完成。bool={}", bool);
    }

    /**
     * 删除博客标签或者用户申请标签临时缓存数据
     */
    private void deleteTagCache() {
        redisHandler.fuzzyDelete(RedisConstant.SYSTEM_TAG_LIST + RedisConstant.ASTERISK);
    }
}